package com.elong.android.specialhouse.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

public class PreferenceTextView extends TextView {
	private OnPreferenceChangedListener m_listener;
	private TextConverter m_textConverter;
	private String m_valueText;

	public PreferenceTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public void setOnPreferenceChangedListener(OnPreferenceChangedListener listener) {
		m_listener = listener;
	}

	public void setTextConverter(TextConverter converter) {
		m_textConverter = converter;
	}

	public void setText(CharSequence text, BufferType type) {
		CharSequence oldText = getText();
		if (m_textConverter != null) {
			m_valueText = (String) m_textConverter.convertText(text, TextConverter.TYPE_DISPLAY2VALUE);
		} else {
			m_valueText = (String) text;
		}
		super.setText(text, type);
		if (m_listener != null) {
			m_listener.onPreferenceChanged(this, oldText, text);
		}
	}

	public String getValueText() {
		return m_valueText == null ? (String) getText() : m_valueText;
	}

	public void setValueText(String text) {
		m_valueText = text;
		if (m_textConverter != null) {
			setText(m_textConverter.convertText(text, TextConverter.TYPE_VALUE2DISPLAY));
		}
		if (getText() == null) {
			setText(m_valueText);
		}
	}

	public static interface OnPreferenceChangedListener {
		public void onPreferenceChanged(PreferenceTextView view, CharSequence oldText, CharSequence newText);
	}

	public static interface TextConverter {
		public final static int TYPE_VALUE2DISPLAY = 0;
		public final static int TYPE_DISPLAY2VALUE = 1;

		public CharSequence convertText(CharSequence text, int type);
	}
}
